//
//  TJGroupChatController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJGroupChatController.h"
#import "TUIDefine.h"
#import "HJChatGroupModel.h"
#import "HJIM.h"
#import "HJGroupSettingController.h"

@interface HJGroupChatController ()

@property (nonatomic, strong) HJChatGroupModel *groupModel;

@end

@implementation HJGroupChatController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.rightBarButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"setting_icon"] target:self action:@selector(didClickGroupSettingButton)];
    [self loadGroupInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshGroupInfoNotification:) name:refreshGroupInfoNotification object:nil];
}


- (void)handleRefreshGroupInfoNotification:(NSNotification *)not {
    NSString *sessionId = not.object;
    if ([sessionId isEqualToString:self.sessionModel.sessionId]) {
        [self loadGroupInfo];
    }
}

- (void)didClickGroupSettingButton {
    if (!_groupModel) {
        _groupModel = [[HJChatGroupModel alloc] init];
        _groupModel.groupId = self.sessionModel.sessionId;
        _groupModel.name = self.sessionModel.sessionName;
        _groupModel.avatar = self.sessionModel.sessionAvatar;
    }
    HJGroupSettingController *groupSettingController = [[HJGroupSettingController alloc] init];
    groupSettingController.groupModel = self.groupModel;
    [self.navigationController pushViewController:groupSettingController];
}

- (void)loadGroupInfo {
    
    //首次查询, 没有缓存的时候把缓存和群成员数据都查询下来, 加载用户信息, 加载群信息
    dispatch_async_sql_queue(^{
        HJChatGroupModel *groupModel = [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.sessionModel.sessionId];
        NSLog(@"groupModel = %@", groupModel);
        self.groupModel = groupModel;
        if (!groupModel) {
            [HJIM.shareIM.groupManager loadGroupMemberListWithGroupId:self.sessionModel.sessionId completion:^(NSArray<HJChatUserModel *> * _Nullable datas) {
                    
            }];
        }
        
        [HJIM.shareIM.groupManager loadGroupInfoByGroupId:self.sessionModel.sessionId completion:^(HJChatGroupModel * _Nullable groupModel) {
            if (!groupModel) return;
            
            self.groupModel = groupModel;

            BOOL isUpdate = !([groupModel.avatar isEqualToString:self.sessionModel.sessionAvatar] && [groupModel.name isEqualToString:self.sessionModel.sessionName]);
            if (isUpdate) {
                
                [HJIM.shareIM.conversationManager getConversationBySessionId:self.sessionModel.sessionId completion:^(HJChatSessionModel * _Nonnull sessionModel) {
                    sessionModel.sessionAvatar = groupModel.avatar;
                    sessionModel.sessionName = groupModel.name;
                    [sessionModel bg_saveOrUpdate];
                    [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
                }];
            }
        }];
    });
    

}

- (void)sendMediaMessageByFileURLs:(NSArray <NSURL *> *)fileURLs photo:(NSArray <UIImage *> *)photo {
    dispatch_async_queue(^{
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
        for (int i = 0; i < fileURLs.count; i++) {
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            [self sendMediaMessageByFileURL:fileURLs[i] photo:photo[i] completion:^{
                dispatch_semaphore_signal(semaphore);
            }];
        }
    });
}

- (void)sendTextMessageByText:(NSString *)text {
    
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = HJChatTypeGroup;
    messageModel.content = text;
    messageModel.groupId = self.sessionModel.sessionId;
    [[HJIM shareIM].chatManager sendTextMessageWithModel:messageModel begin:^(HJChatMessageModel * _Nonnull model) {
        [self updateMessageWithMessageModel:model];
    } completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
        
    }];
    
}

- (void)sendMediaMessageByAssets:(NSArray<PHAsset *> *)asset photo:(NSArray<UIImage *> *)photo {
    dispatch_async_queue(^{
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
        for (int i = 0; i < asset.count; i++) {
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            [self sendMediaMessageByAsset:asset[i] photo:photo[i] completion:^{
                dispatch_semaphore_signal(semaphore);
            }];
        }
    });
}

- (void)sendMediaMessageByFileURL:(NSURL *)fileURL photo:(UIImage *)photo completion:(void (^)(void))completion {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    
    messageModel.chatType = HJChatTypeGroup;
    messageModel.fileURL = fileURL;
    messageModel.originalImage = photo;
    messageModel.groupId = self.sessionModel.sessionId;
    [[HJIM shareIM].chatManager sendMediaMessageWithModel:messageModel begin:^(HJChatMessageModel * _Nonnull model) {
        [self updateMessageWithMessageModel:model];
        completion();
    } completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
        
    }];
}


- (void)sendImageMessageByLocalPath:(NSString *)localPath {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = HJChatTypeGroup;
    messageModel.localPath = localPath;
    messageModel.groupId = self.sessionModel.sessionId;
    [[HJIM shareIM].chatManager sendImageMessageWithModel:messageModel begin:^(HJChatMessageModel * _Nonnull model) {
        [self updateMessageWithMessageModel:model];
    } completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
        
    }];
}

- (void)sendVideoMessageByLocalPath:(NSString *)localPath photo:(UIImage *)photo {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = HJChatTypeGroup;
    messageModel.localPath = localPath;
    messageModel.originalImage = photo;
    messageModel.groupId = self.sessionModel.sessionId;
    [[HJIM shareIM].chatManager sendVideoMessageWithModel:messageModel begin:^(HJChatMessageModel * _Nonnull model) {
        [self updateMessageWithMessageModel:model];
    } completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
        
    }];
}

- (void)sendFileMessageByUrl:(NSURL *)URL {
    
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = HJChatTypeGroup;
    messageModel.fileURL = URL;
    messageModel.groupId = self.sessionModel.sessionId;
    [[HJIM shareIM].chatManager sendFileMessageWithModel:messageModel begin:^(HJChatMessageModel * _Nonnull model) {
        [self updateMessageWithMessageModel:model];
    } completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
        
    }];
}

- (void)sendVoiceMessageByLocalPath:(NSString *)localPath {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = HJChatTypeGroup;
    messageModel.localPath = localPath;
    messageModel.groupId = self.sessionModel.sessionId;
    [[HJIM shareIM].chatManager sendVoiceMessageWithModel:messageModel begin:^(HJChatMessageModel * _Nonnull model) {
        [self updateMessageWithMessageModel:model];
    } completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
        
    }];
}

- (void)updateMessageWithMessageModel:(HJChatMessageModel *)model {
    HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:model];
    [self.messageController addNewMessage:messageLayout];
}

- (void)sendVoiceMessageBySecond:(NSInteger)second fileName:(NSString *)fileName filePath:(NSString *)audioPath{
    
    
    
}


- (void)sendMediaMessageByAsset:(PHAsset *)asset photo:(UIImage *)photo completion:(void (^)(void))completion {
    
    
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%s", __func__);
}


@end
